package com.jl15988.chainlog.callback;

import com.jl15988.chainlog.model.ChainApiLog;
import com.jl15988.chainlog.model.ChainMethodLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 默认链式监控回调实现
 */
public class DefaultChainMethodCallback implements ChainMethodCallback {

    private static final Logger logger = LoggerFactory.getLogger(DefaultChainMethodCallback.class);

    @Override
    public void onChainComplete(ChainMethodLog chainMethodLog, ChainApiLog chainApiLog, ChainMethodLog parentChainMethodLog) {
        logger.info("Chain Monitor Complete: {}", formatChainInfo(chainMethodLog, chainApiLog, parentChainMethodLog));
    }

    @Override
    public void onChainException(ChainMethodLog chainMethodLog, ChainApiLog chainApiLog,
                                        ChainMethodLog parentChainMethodLog, Throwable exception) {
        logger.error("Chain Monitor Exception: {}", formatChainInfo(chainMethodLog, chainApiLog, parentChainMethodLog), exception);
    }

    private String formatChainInfo(ChainMethodLog chainMethodLog, ChainApiLog chainApiLog, ChainMethodLog parentChainMethodLog) {
        StringBuilder sb = new StringBuilder();
        sb.append("ChainID=").append(chainMethodLog.getId())
                .append(", ParentID=").append(chainMethodLog.getParentId())
                .append(", ApiID=").append(chainApiLog.getId())
                .append(", Method=").append(chainMethodLog.getMethod())
                .append(", Name=").append(chainMethodLog.getName())
                .append(", Level=").append(chainMethodLog.getLevel())
                .append(", Duration=").append(chainMethodLog.getDuration()).append("ms")
                .append(", Success=").append(chainMethodLog.isSuccess());

        if (chainMethodLog.getDesc() != null && !chainMethodLog.getDesc().isEmpty()) {
            sb.append(", Remark=").append(chainMethodLog.getDesc());
        }

        if (parentChainMethodLog != null) {
            sb.append(", ParentMethod=").append(parentChainMethodLog.getMethod());
        }

        return sb.toString();
    }
}